package com.expense.app.admin.services.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.expense.app.admin.common.BaseService;
import com.expense.app.admin.model.dto.student.*;
import com.expense.app.admin.model.params.student.*;
import com.expense.app.admin.services.StudentServ;
import com.expense.common.constant.enums.DeletedStatus;
import com.expense.common.dao.StudentDao;
import com.expense.common.exception.PlatformException;
import com.expense.common.model.Student;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 学生信息
 */
@Service
public class StudentServImpl extends BaseService implements StudentServ {
    private static final Log log = LogFactory.get();

    @Autowired
    StudentDao studentDao;

    @Override
    public StudentImportDTO importExcel(StudentImportParam param) {
        List<Map<String,String>> list = param.getMapList();
        List<String> telList = param.getTelList();

        Map<String, Object> telMap = new HashMap<>();
        telMap.put("tels",telList);
        List<Student> studentListByTel = studentDao.findListByTel(telMap);

        List<Student> studentList = new ArrayList<>();
        List<String> successList = new ArrayList<>();
        List<String> errorList = new ArrayList<>();
        if(list != null && list.size()>0) {
            list.stream().forEach(map->{
                String name = map.get("姓名");
                String sex = map.get("性别");
                String tel = map.get("电话");
                String mail = map.get("邮件");
                String school = map.get("院校");
                String major = map.get("专业");
                String study = map.get("研究方向");
                String education = map.get("学历");
                String graduate = map.get("毕业时间");
                String city = map.get("所在城市");

                Map<String, String> errorData = new HashMap<>();
                errorData.put("name", name);
                errorData.put("sex", sex);
                errorData.put("tel", tel);
                errorData.put("mail", mail);
                errorData.put("school", school);
                errorData.put("major", major);
                errorData.put("study", study);
                errorData.put("education", education);
                errorData.put("graduate", graduate);

                if (StrUtil.isBlank(name) || StrUtil.isBlank(school) || StrUtil.isBlank(tel)) {
                    errorList.add("1");
                    return;
                }
                if(11 != tel.length()){
                    errorList.add("1");
                    return;
                }

                Student student = new Student();
                setBaseInfo(student);
                student.setName(name);
                student.setSex(sex);
                student.setTel(tel);
                student.setMail(mail);
                student.setSchool(school);
                student.setMajor(major);
                student.setStudy(study);
                student.setEducation(education);
                student.setGraduate(graduate);
                student.setCity(city);

                //tel 是唯一
                // 数据发生变更也能插入
                if(studentListByTel.size() != 0) {
                    if (!findByTel(studentListByTel, student)) {
                        errorList.add("1");
                        return;
                    }
                }

                successList.add("1");
                studentList.add(student);
            });

        }
        StudentImportDTO studentImportDTO = new StudentImportDTO();
        studentImportDTO.setErrorCount(errorList.size());
        studentImportDTO.setSuccessCount(successList.size());
        studentImportDTO.setSuccessList(studentList);
        return studentImportDTO;
    }

    public Boolean findByTel(List<Student > studentListByTel, Student student){
        //Student s = studentDao.findByTel(tel);
        for(Student s : studentListByTel){
            if(!s.getName().equals(student.getName())){
                return true;
            }else if(!(s.getSex() == null ? student.getSex() == null :s.getSex().equals(student.getSex()))){
                return true;
            }else if(!(s.getMail() == null ? student.getMail() == null : s.getMail().equals(student.getMail()))){
                return true;
            }else if(!s.getSchool().equals(student.getSchool())){
                return true;
            }else if(!(s.getMajor() ==null ? student.getMajor() == null :s.getMajor().equals(student.getMajor()))){
                return true;
            }else if(!(s.getStudy() ==null ? student.getStudy() == null : s.getStudy().equals(student.getStudy()))){
                return true;
            }else if(!(s.getEducation() ==null ? student.getEducation() == null :s.getEducation().equals(student.getEducation()))){
                return true;
            }else if(!(s.getGraduate() ==null ? student.getGraduate() == null :s.getGraduate().equals(student.getGraduate()))){
                return true;
            }else if(!(s.getCity() ==null ? student.getCity() == null :s.getCity().equals(student.getCity()))){
                return true;
            }else{
                return false;
            }
        }
        return true;
    }

    @Override
    public StudentListDTO findList(StudentListParam param) {
        Map<String,Object> condition = new HashMap<>();
        condition.put("key",param.getKey());
        condition.put("school",param.getSchool());
        condition.put("major",param.getMajor());
        condition.put("education",param.getEducation());
        PageQuery pageQuery = initPageQuery(param.getPage(),param.getSort());
        pageQuery.setParas(condition);
        studentDao.findListPage(pageQuery);
        return new StudentListDTO(pageQuery.getList(),pageQuery.getTotalRow());
    }

    @Override
    public StudentListDTO findListByParam(StudentExportParam param) {
        Map<String,Object> condition = new HashMap<>();
        /*if(param.getSchool().size() != 0){
            List<String> school = new ArrayList<>();
            for(String str : param.getSchool()){
                StringBuffer name = new StringBuffer();
                String [] strs = str.split("",2);
                name.append(strs[0]);
                if(!StringUtils.isEmpty(strs[1])){
                    //添加 %% 为了 查询 北大 能查询到 北京大学
                    name.append("%%"+strs[1]);
                }
                school.add(str);
            }
            condition.put("schools", school);
        }*/
        condition.put("schools", setList(param.getSchool()));
        condition.put("sex", param.getSex());
        if(param.getEducation().size()>0){
            condition.put("educations", param.getEducation());
        }else{
            condition.put("educations", null);
        }
        if(null != param.getMajor()){
            condition.put("majors", setList(param.getMajor()));
        }
        if(null != param.getCity()){
            condition.put("citys", setList(param.getCity()));
        }
        if(null != param.getGraduate()){
            condition.put("graduates", setList(param.getGraduate()));
        }
        if(null != param.getStudy()){
            condition.put("studys", setList(param.getStudy()));
        }
        PageQuery pageQuery = initPageQuery(param.getPage(),param.getSort());
        pageQuery.setParas(condition);
        List<Student> list = studentDao.findListByParam( condition);
        StudentListDTO studentListDTO = new StudentListDTO(list, Long.valueOf(list.size()));
        return studentListDTO;
    }

    public List<String> setList(String param){
        String [] strs = param.split(",");
        List<String> list = new ArrayList<>();
        for(String str : strs){
            if(!StringUtils.isEmpty(str)){
                list.add(str);
            }
        }
        if(list.size()>0){
            return list;
        }else{
            return null;
        }
    }

    @Override
    public Student findOne(Long id) {
        return studentDao.findByIdAndDeleted(id);
    }

    @Override
    public StudentDTO findDetail(Long id) {
        Student entity = studentDao.findByIdAndDeleted(id);
        return new StudentDTO(entity);
    }

    @Override
    @Transactional
    public int saveList(StudentParam param) {
        studentDao.saveAll(param.getList());
        //其他关联处理
        return 1;
    }
    /*public Student saveOne(StudentParam param) {
        Student entity = param.getEntity();
        setBaseInfo(entity);
        studentDao.saveOne(entity);
        //其他关联处理
        return entity;
    }*/

    @Override
    public Long deleteOne(Long id) {
        Student entity = studentDao.findByIdAndDeleted(id);
        if(entity == null) throw new PlatformException("学生信息已不存在");
        entity.setDeleted(DeletedStatus.DELETED);
        setBaseInfo(entity);
        studentDao.updateTemplateById(entity);
        //其他关联处理
        return id;
    }
}
